﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace JEng_Mark_1.GameComponents
{
    public class JFpsCounter : GameComponent
    {
        private float _updateInterval = 1.0f;
        private float _timeSinceLastUpdate = 0.0f;
        private float _framecount = 0;

        private float _fps = 0.0f;

        /// <summary>
        /// The frames per second
        /// </summary>
        public float FPS { get { return _fps; } }

        public JFpsCounter(Game game)
            : base(game)
        {
            Enabled = true;
        }

        /// <summary>
        /// Update the fps counter
        /// </summary>
        /// <param name="gameTime">Timing snapshot</param>
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            float elapsed = (float)gameTime.ElapsedRealTime.TotalSeconds;
            _framecount++;
            _timeSinceLastUpdate += elapsed;

            if (_timeSinceLastUpdate > _updateInterval)
            {
                _fps = _framecount / _timeSinceLastUpdate;
                _framecount = 0;
                _timeSinceLastUpdate -= _updateInterval;

                if (Updated != null)
                    Updated(this, new EventArgs());
            }
        }

        /// <summary>
        /// FpsCount Updated Event
        /// </summary>
        public event EventHandler<EventArgs> Updated;
    }
}
